/*
 * Copyright (C) 2018 Baidu, Inc. All Rights Reserved.
 */
package com.sailboard.iot.opm.web.controller.qrcode;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.sailboard.iot.opm.service.qrcode.QrCodeFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author: liyl
 * @date: 2017/11/26 下午8:48
 * @since 1.0.0
 * 二维码管理
 */
@RestController
@RequestMapping("/v1/api0/qrcode/")
public class QrCodeController {

    @Autowired
    private QrCodeFactory qrCodeFactory;

    @RequestMapping(value = "test", method = RequestMethod.GET)
    public ModelAndView test() {
        ModelAndView modelAndView= new ModelAndView("qrcode/qrcode");
        return modelAndView;
    }

    @RequestMapping(value = "get")
    public void get(HttpServletResponse response) {
        BitMatrix bitMatrix = qrCodeFactory.create("http://www.baidu.com");
        response.setContentType("img/jpeg");
        response.setCharacterEncoding("utf-8");
        try {

            OutputStream outputStream = response.getOutputStream();
            BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
            ImageIO.write(bufferedImage, "png", outputStream);
            outputStream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
